package xiaopiya.robot.handler.main;

import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;

import xiaopiya.robot.handler.IMessageHandler;

/**
 * @author Ray (ayufox@gmail.com)
 * @version 0.1
 */
public class MainMessageHandler implements IMessageHandler
{
	protected final Log LOG = LogFactory.getLog(getClass());

	// 默认处理命令
	private final static String DEFAULT_HANDLE_COMMAND = "fy";

	private String defaultHandleCommand = DEFAULT_HANDLE_COMMAND;

	private Map<String, IMessageHandler> handlers;
	
	public void setDefaultHandleCommand(String defaultHandleCommand)
	{
		this.defaultHandleCommand = defaultHandleCommand;
	}

	public String getDefaultHandleCommand()
	{
		return defaultHandleCommand;
	}

	public void setHandlers(Map<String, IMessageHandler> handlers)
	{
		this.handlers = handlers;
	}

	protected IMessageHandler getHandler(String name)
	{
		return this.handlers.get(name);
	}

	public void handle(XMPPConnection connection, Chat chat, Message message,
			String messageBody) throws XMPPException
	{
		String command = this.defaultHandleCommand;
		if (messageBody.startsWith(":"))
		{
			int splitIndex = messageBody.indexOf(' ');
			if (splitIndex < 0)
			{
				command = messageBody;
			} else
			{
				command = messageBody.substring(0, splitIndex);
			}
			messageBody = messageBody.substring(command.length(),
					messageBody.length()).trim();
			command = command.substring(1, command.length());
		}

		command = command.toLowerCase();

		IMessageHandler messageHandler = getHandler(command);
		if (messageHandler == null)
		{
			if (LOG.isInfoEnabled())
			{
				LOG.info("command [" + command + "] not supported from "
						+ chat.getParticipant());
			}
			String msg = (getCommandError(command, messageBody));
			if (msg != null)
			{
				chat.sendMessage(msg);
			}
		} else
		{
			messageHandler.handle(connection, chat, message, messageBody);
		}
	}

	protected String getCommandError(String command, String messageBody)
	{
		return "不支持" + command + "命令，请键入:help或:bz获得更多帮忙";
	}
}
